﻿
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Primitives;
using MX.Core.Log;
using Nop.Core;
using Nop.Core.Caching;
using Nop.Core.Configuration;
using Nop.Core.Domain;
using Nop.Core.Domain.Common;
using Nop.Core.Domain.Customers;
using Nop.Core.Domain.Forums;
using Nop.Core.Domain.Gdpr;
using Nop.Core.Domain.Localization;
using Nop.Core.Domain.Media;
using Nop.Core.Domain.Messages;
using Nop.Core.Domain.Tax;
using Nop.Services.Authentication;
using Nop.Services.Authentication.External;
using Nop.Services.Catalog;
using Nop.Services.Common;
using Nop.Services.Customers;
using Nop.Services.Directory;
using Nop.Services.Events;
using Nop.Services.ExportImport;
using Nop.Services.Gdpr;
using Nop.Services.Helpers;
using Nop.Services.Localization;
using Nop.Services.Logging;
using Nop.Services.Media;
using Nop.Services.Messages;
using Nop.Services.Orders;
using Nop.Services.Tax;
using Nop.Web.Areas.App.Models;
using Nop.Web.Factories;
using Nop.Web.Models.Customer;
using Nop.Web.Services.Easemob;
using Nop.Web.Services.Utils;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using UserCenter.Console.Sdk;

namespace Nop.Web.Areas.App.Attributes
{
    public class UserCenterAttribute : TypeFilterAttribute
    {
        public UserCenterAttribute() : base(typeof(UserCenterFilter))
        {
            // MemberSdk memberSdk = new MemberSdk();
        }

        private class UserCenterFilter : IActionFilter
        {
            static Dictionary<string, AutoResetEvent> processMutexList = new Dictionary<string, AutoResetEvent>();
            static ConcurrentDictionary<string, int> tokenOfCustomerIdDict = new ConcurrentDictionary<string, int>();

            private readonly IStaticCacheManager _cacheManager;
            private readonly NopConfig _config;
            private readonly AddressSettings _addressSettings;
            private readonly CustomerSettings _customerSettings;
            private readonly DateTimeSettings _dateTimeSettings;
            private readonly ForumSettings _forumSettings;
            private readonly GdprSettings _gdprSettings;
            private readonly IAddressAttributeParser _addressAttributeParser;
            private readonly IAddressModelFactory _addressModelFactory;
            private readonly IAddressService _addressService;
            private readonly IAuthenticationService _authenticationService;
            private readonly ICountryService _countryService;
            private readonly ICurrencyService _currencyService;
            private readonly ICustomerActivityService _customerActivityService;
            private readonly ICustomerAttributeParser _customerAttributeParser;
            private readonly ICustomerAttributeService _customerAttributeService;
            private readonly ICustomerModelFactory _customerModelFactory;
            private readonly ICustomerRegistrationService _customerRegistrationService;
            private readonly ICustomerService _customerService;
            private readonly IEventPublisher _eventPublisher;
            private readonly IExportManager _exportManager;
            private readonly IExternalAuthenticationService _externalAuthenticationService;
            private readonly IGdprService _gdprService;
            private readonly IGenericAttributeService _genericAttributeService;
            private readonly IGiftCardService _giftCardService;
            private readonly ILocalizationService _localizationService;
            private readonly INewsLetterSubscriptionService _newsLetterSubscriptionService;
            private readonly IOrderService _orderService;
            private readonly IPictureService _pictureService;
            private readonly IPriceFormatter _priceFormatter;
            private readonly IShoppingCartService _shoppingCartService;
            private readonly IStoreContext _storeContext;
            private readonly ITaxService _taxService;
            private readonly IWebHelper _webHelper;
            private readonly IWorkContext _workContext;
            private readonly IWorkflowMessageService _workflowMessageService;
            private readonly LocalizationSettings _localizationSettings;
            private readonly MediaSettings _mediaSettings;
            private readonly StoreInformationSettings _storeInformationSettings;
            private readonly TaxSettings _taxSettings;
            private readonly HUCSdkHelper _hUCSdkHelper;
            private readonly EasemobManager _easemobManager;

            public UserCenterFilter(
                HUCSdkHelper hUCSdkHelper,
                NopConfig config,
                IStaticCacheManager cacheManager,
                AddressSettings addressSettings,
                CustomerSettings customerSettings,
                DateTimeSettings dateTimeSettings,
                IDownloadService downloadService,
                ForumSettings forumSettings,
                GdprSettings gdprSettings,
                IAddressAttributeParser addressAttributeParser,
                IAddressModelFactory addressModelFactory,
                IAddressService addressService,
                IAuthenticationService authenticationService,
                ICountryService countryService,
                ICurrencyService currencyService,
                ICustomerActivityService customerActivityService,
                ICustomerAttributeParser customerAttributeParser,
                ICustomerAttributeService customerAttributeService,
                ICustomerModelFactory customerModelFactory,
                ICustomerRegistrationService customerRegistrationService,
                ICustomerService customerService,
                IEventPublisher eventPublisher,
                IExportManager exportManager,
                IExternalAuthenticationService externalAuthenticationService,
                IGdprService gdprService,
                IGenericAttributeService genericAttributeService,
                IGiftCardService giftCardService,
                ILocalizationService localizationService,
                INewsLetterSubscriptionService newsLetterSubscriptionService,
                IOrderService orderService,
                IPictureService pictureService,
                IPriceFormatter priceFormatter,
                IShoppingCartService shoppingCartService,
                IStoreContext storeContext,
                ITaxService taxService,
                IWebHelper webHelper,
                IWorkContext workContext,
                IWorkflowMessageService workflowMessageService,
                LocalizationSettings localizationSettings,
                MediaSettings mediaSettings,
                StoreInformationSettings storeInformationSettings,
                TaxSettings taxSettings,
                EasemobManager easemobManager)
            {
                this._hUCSdkHelper = hUCSdkHelper;
                this._config = config;
                this._cacheManager = cacheManager;
                this._addressSettings = addressSettings;
                this._customerSettings = customerSettings;
                this._dateTimeSettings = dateTimeSettings;
                this._forumSettings = forumSettings;
                this._gdprSettings = gdprSettings;
                this._addressAttributeParser = addressAttributeParser;
                this._addressModelFactory = addressModelFactory;
                this._addressService = addressService;
                this._authenticationService = authenticationService;
                this._countryService = countryService;
                this._currencyService = currencyService;
                this._customerActivityService = customerActivityService;
                this._customerAttributeParser = customerAttributeParser;
                this._customerAttributeService = customerAttributeService;
                this._customerModelFactory = customerModelFactory;
                this._customerRegistrationService = customerRegistrationService;
                this._customerService = customerService;
                this._eventPublisher = eventPublisher;
                this._exportManager = exportManager;
                this._externalAuthenticationService = externalAuthenticationService;
                this._gdprService = gdprService;
                this._genericAttributeService = genericAttributeService;
                this._giftCardService = giftCardService;
                this._localizationService = localizationService;
                this._newsLetterSubscriptionService = newsLetterSubscriptionService;
                this._orderService = orderService;
                this._pictureService = pictureService;
                this._priceFormatter = priceFormatter;
                this._shoppingCartService = shoppingCartService;
                this._storeContext = storeContext;
                this._taxService = taxService;
                this._webHelper = webHelper;
                this._workContext = workContext;
                this._workflowMessageService = workflowMessageService;
                this._localizationSettings = localizationSettings;
                this._mediaSettings = mediaSettings;
                this._storeInformationSettings = storeInformationSettings;
                this._taxSettings = taxSettings;
                this._easemobManager = easemobManager;
            }

            public void OnActionExecuted(ActionExecutedContext context)
            {
                //nothing
            }


            void Register(string email, long ucMemberId, string token)
            {
                if (_workContext.CurrentCustomer.IsRegistered())
                {
                    //Already registered customer. 
                    _authenticationService.SignOut();

                    //raise logged out event       
                    _eventPublisher.Publish(new CustomerLoggedOutEvent(_workContext.CurrentCustomer));

                    //Save a new record
                    _workContext.CurrentCustomer = _customerService.InsertGuestCustomer();
                }
                var model = new RegisterModel();
                model = _customerModelFactory.PrepareRegisterModel(model, false, setDefaultValues: true);
                model.Email = email;
                var customer = _workContext.CurrentCustomer;
                customer.RegisteredInStoreId = _storeContext.CurrentStore.Id;
                var isApproved = _customerSettings.UserRegistrationType == UserRegistrationType.Standard;
                var registrationRequest = new CustomerRegistrationRequest(customer,
                                           email, email,
                                            CommonHelper.GenerateRandomDigitCode(20),
                                            PasswordFormat.Clear,
                                            _storeContext.CurrentStore.Id,
                                            isApproved);
                var registrationResult = _customerRegistrationService.RegisterCustomer(registrationRequest);
                if (registrationResult.Success)
                {
                    var registeredRole = _customerService.GetCustomerRoleBySystemName(NopCustomerDefaults.RegisteredRoleName);
                    customer.CustomerRoles.Add(registeredRole);
                    var guestRole = customer.CustomerRoles.FirstOrDefault(cr => cr.SystemName == NopCustomerDefaults.GuestsRoleName);
                    customer.CustomerRoles.Remove(guestRole);

                    //properties
                    if (_dateTimeSettings.AllowCustomersToSetTimeZone)
                    {
                        _genericAttributeService.SaveAttribute(customer, NopCustomerDefaults.TimeZoneIdAttribute, model.TimeZoneId);
                    }
                    //VAT number
                    if (_taxSettings.EuVatEnabled)
                    {
                        _genericAttributeService.SaveAttribute(customer, NopCustomerDefaults.VatNumberAttribute, model.VatNumber);

                        var vatNumberStatus = _taxService.GetVatNumberStatus(model.VatNumber, out string _, out string vatAddress);
                        _genericAttributeService.SaveAttribute(customer, NopCustomerDefaults.VatNumberStatusIdAttribute, (int)vatNumberStatus);
                        //send VAT number admin notification
                        if (!string.IsNullOrEmpty(model.VatNumber) && _taxSettings.EuVatEmailAdminWhenNewVatSubmitted)
                            _workflowMessageService.SendNewVatSubmittedStoreOwnerNotification(customer, model.VatNumber, vatAddress, _localizationSettings.DefaultAdminLanguageId);
                    }

                    //form fields
                    if (_customerSettings.GenderEnabled)
                        _genericAttributeService.SaveAttribute(customer, NopCustomerDefaults.GenderAttribute, model.Gender);
                    _genericAttributeService.SaveAttribute(customer, NopCustomerDefaults.FirstNameAttribute, model.FirstName);
                    _genericAttributeService.SaveAttribute(customer, NopCustomerDefaults.LastNameAttribute, model.LastName);
                    if (_customerSettings.DateOfBirthEnabled)
                    {
                        var dateOfBirth = model.ParseDateOfBirth();
                        _genericAttributeService.SaveAttribute(customer, NopCustomerDefaults.DateOfBirthAttribute, dateOfBirth);
                    }
                    if (_customerSettings.CompanyEnabled)
                        _genericAttributeService.SaveAttribute(customer, NopCustomerDefaults.CompanyAttribute, model.Company);
                    if (_customerSettings.StreetAddressEnabled)
                        _genericAttributeService.SaveAttribute(customer, NopCustomerDefaults.StreetAddressAttribute, model.StreetAddress);
                    if (_customerSettings.StreetAddress2Enabled)
                        _genericAttributeService.SaveAttribute(customer, NopCustomerDefaults.StreetAddress2Attribute, model.StreetAddress2);
                    if (_customerSettings.ZipPostalCodeEnabled)
                        _genericAttributeService.SaveAttribute(customer, NopCustomerDefaults.ZipPostalCodeAttribute, model.ZipPostalCode);
                    if (_customerSettings.CityEnabled)
                        _genericAttributeService.SaveAttribute(customer, NopCustomerDefaults.CityAttribute, model.City);
                    if (_customerSettings.CountyEnabled)
                        _genericAttributeService.SaveAttribute(customer, NopCustomerDefaults.CountyAttribute, model.County);
                    if (_customerSettings.CountryEnabled)
                        _genericAttributeService.SaveAttribute(customer, NopCustomerDefaults.CountryIdAttribute, model.CountryId);
                    if (_customerSettings.CountryEnabled && _customerSettings.StateProvinceEnabled)
                        _genericAttributeService.SaveAttribute(customer, NopCustomerDefaults.StateProvinceIdAttribute,
                            model.StateProvinceId);
                    if (_customerSettings.PhoneEnabled)
                        _genericAttributeService.SaveAttribute(customer, NopCustomerDefaults.PhoneAttribute, model.Phone);
                    if (_customerSettings.FaxEnabled)
                        _genericAttributeService.SaveAttribute(customer, NopCustomerDefaults.FaxAttribute, model.Fax);

                    //newsletter
                    if (_customerSettings.NewsletterEnabled)
                    {
                        //save newsletter value
                        var newsletter = _newsLetterSubscriptionService.GetNewsLetterSubscriptionByEmailAndStoreId(model.Email, _storeContext.CurrentStore.Id);
                        if (newsletter != null)
                        {
                            if (model.Newsletter)
                            {
                                newsletter.Active = true;
                                _newsLetterSubscriptionService.UpdateNewsLetterSubscription(newsletter);

                                //GDPR
                                if (_gdprSettings.GdprEnabled && _gdprSettings.LogNewsletterConsent)
                                {
                                    _gdprService.InsertLog(customer, 0, GdprRequestType.ConsentAgree, _localizationService.GetResource("Gdpr.Consent.Newsletter"));
                                }
                            }
                            //else
                            //{
                            //When registering, not checking the newsletter check box should not take an existing email address off of the subscription list.
                            //_newsLetterSubscriptionService.DeleteNewsLetterSubscription(newsletter);
                            //}
                        }
                        else
                        {
                            if (model.Newsletter)
                            {
                                _newsLetterSubscriptionService.InsertNewsLetterSubscription(new NewsLetterSubscription
                                {
                                    NewsLetterSubscriptionGuid = Guid.NewGuid(),
                                    Email = model.Email,
                                    Active = true,
                                    StoreId = _storeContext.CurrentStore.Id,
                                    CreatedOnUtc = DateTime.UtcNow
                                });

                                //GDPR
                                if (_gdprSettings.GdprEnabled && _gdprSettings.LogNewsletterConsent)
                                {
                                    _gdprService.InsertLog(customer, 0, GdprRequestType.ConsentAgree, _localizationService.GetResource("Gdpr.Consent.Newsletter"));
                                }
                            }
                        }
                    }

                    if (_customerSettings.AcceptPrivacyPolicyEnabled)
                    {
                        //privacy policy is required
                        //GDPR
                        if (_gdprSettings.GdprEnabled && _gdprSettings.LogPrivacyPolicyConsent)
                        {
                            _gdprService.InsertLog(customer, 0, GdprRequestType.ConsentAgree, _localizationService.GetResource("Gdpr.Consent.PrivacyPolicy"));
                        }
                    }

                    //GDPR
                    if (_gdprSettings.GdprEnabled)
                    {
                        var consents = _gdprService.GetAllConsents().Where(consent => consent.DisplayDuringRegistration).ToList();
                        foreach (var consent in consents)
                        {
                            var controlId = $"consent{consent.Id}";
                            var cbConsent = model.Form[controlId];
                            if (!StringValues.IsNullOrEmpty(cbConsent) && cbConsent.ToString().Equals("on"))
                            {
                                //agree
                                _gdprService.InsertLog(customer, consent.Id, GdprRequestType.ConsentAgree, consent.Message);
                            }
                            else
                            {
                                //disagree
                                _gdprService.InsertLog(customer, consent.Id, GdprRequestType.ConsentDisagree, consent.Message);
                            }
                        }
                    }

                    //save customer attributes
                    _genericAttributeService.SaveAttribute(customer, NopCustomerDefaults.CustomCustomerAttributes, "");

                    //login customer now
                    if (isApproved)
                        _authenticationService.SignIn(customer, true);

                    //insert default address (if possible)
                    var defaultAddress = new Address
                    {
                        FirstName = _genericAttributeService.GetAttribute<string>(customer, NopCustomerDefaults.FirstNameAttribute),
                        LastName = _genericAttributeService.GetAttribute<string>(customer, NopCustomerDefaults.LastNameAttribute),
                        Email = customer.Email,
                        Company = _genericAttributeService.GetAttribute<string>(customer, NopCustomerDefaults.CompanyAttribute),
                        CountryId = _genericAttributeService.GetAttribute<int>(customer, NopCustomerDefaults.CountryIdAttribute) > 0
                            ? (int?)_genericAttributeService.GetAttribute<int>(customer, NopCustomerDefaults.CountryIdAttribute)
                            : null,
                        StateProvinceId = _genericAttributeService.GetAttribute<int>(customer, NopCustomerDefaults.StateProvinceIdAttribute) > 0
                            ? (int?)_genericAttributeService.GetAttribute<int>(customer, NopCustomerDefaults.StateProvinceIdAttribute)
                            : null,
                        County = _genericAttributeService.GetAttribute<string>(customer, NopCustomerDefaults.CountyAttribute),
                        City = _genericAttributeService.GetAttribute<string>(customer, NopCustomerDefaults.CityAttribute),
                        Address1 = _genericAttributeService.GetAttribute<string>(customer, NopCustomerDefaults.StreetAddressAttribute),
                        Address2 = _genericAttributeService.GetAttribute<string>(customer, NopCustomerDefaults.StreetAddress2Attribute),
                        ZipPostalCode = _genericAttributeService.GetAttribute<string>(customer, NopCustomerDefaults.ZipPostalCodeAttribute),
                        PhoneNumber = _genericAttributeService.GetAttribute<string>(customer, NopCustomerDefaults.PhoneAttribute),
                        FaxNumber = _genericAttributeService.GetAttribute<string>(customer, NopCustomerDefaults.FaxAttribute),
                        CreatedOnUtc = customer.CreatedOnUtc
                    };
                    if (this._addressService.IsAddressValid(defaultAddress))
                    {
                        //some validation
                        if (defaultAddress.CountryId == 0)
                            defaultAddress.CountryId = null;
                        if (defaultAddress.StateProvinceId == 0)
                            defaultAddress.StateProvinceId = null;
                        //set default address
                        //customer.Addresses.Add(defaultAddress);
                        customer.CustomerAddressMappings.Add(new CustomerAddressMapping { Address = defaultAddress });
                        customer.BillingAddress = defaultAddress;
                        customer.ShippingAddress = defaultAddress;
                        _customerService.UpdateCustomer(customer);
                    }

                    //notifications
                    if (_customerSettings.NotifyNewCustomerRegistration)
                        _workflowMessageService.SendCustomerRegisteredNotificationMessage(customer,
                            _localizationSettings.DefaultAdminLanguageId);

                    //raise event       
                    _eventPublisher.Publish(new CustomerRegisteredEvent(customer));

                    switch (_customerSettings.UserRegistrationType)
                    {
                        case UserRegistrationType.EmailValidation:
                            {
                                //email validation message
                                _genericAttributeService.SaveAttribute(customer, NopCustomerDefaults.AccountActivationTokenAttribute, Guid.NewGuid().ToString());
                                _workflowMessageService.SendCustomerEmailValidationMessage(customer, _workContext.WorkingLanguage.Id);

                                break;

                            }
                        case UserRegistrationType.Standard:
                            {
                                //send customer welcome message
                                _workflowMessageService.SendCustomerWelcomeMessage(customer, _workContext.WorkingLanguage.Id);

                                break;
                            }
                    }
                    _genericAttributeService.SaveAttribute<long>(customer, "NOP_UCMemberId", ucMemberId);

                    _workContext.CurrentCustomer = customer;

                    tokenOfCustomerIdDict[token] = customer.Id;
                    DebugLog($"Url: Token:{token}注册完成写入结果集{customer.Id},Email:{customer.Email}");

                }
            }


            void Login(string token, Customer customer)
            {
                //migrate shopping cart
                _shoppingCartService.MigrateShoppingCart(_workContext.CurrentCustomer, customer, true);

                //sign in new customer
                _authenticationService.SignIn(customer, true);

                //raise event       
                _eventPublisher.Publish(new CustomerLoggedinEvent(customer));

                //activity log
                _customerActivityService.InsertActivity(customer, "PublicStore.Login",
                    _localizationService.GetResource("ActivityLog.PublicStore.Login"), customer);


                _workContext.CurrentCustomer = customer;
                tokenOfCustomerIdDict[token] = customer.Id;
                DebugLog($"Url:,Token:{token}登录完成写入结果集{customer.Id},Email:{customer.Email}");

            }

            void Logout()
            {
                //activity log
                _customerActivityService.InsertActivity(_workContext.CurrentCustomer, "PublicStore.Logout",
                    _localizationService.GetResource("ActivityLog.PublicStore.Logout"), _workContext.CurrentCustomer);

                //standard logout 
                _authenticationService.SignOut();

                //raise logged out event       
                _eventPublisher.Publish(new CustomerLoggedOutEvent(_workContext.CurrentCustomer));
                _workContext.CurrentCustomer = null;
            }

            void SetCustomer(string token)
            {


                if (!_workContext.CurrentCustomer.IsRegistered())
                {
                    _workContext.CurrentCustomer = _customerService.GetCustomerById(tokenOfCustomerIdDict[token]);
                    if (!_workContext.CurrentCustomer.IsRegistered())
                    {
                        var realCustomer = _customerService.GetCustomerByIdWithNoTracking(tokenOfCustomerIdDict[token]);
                        var registeredRole = _customerService.GetCustomerRoleBySystemName(NopCustomerDefaults.RegisteredRoleName);
                        _workContext.CurrentCustomer.CustomerRoles.Add(registeredRole);
                        var guestRole = _workContext.CurrentCustomer.CustomerRoles.FirstOrDefault(cr => cr.SystemName == NopCustomerDefaults.GuestsRoleName);
                        _workContext.CurrentCustomer.CustomerRoles.Remove(guestRole);
                        _workContext.CurrentCustomer.Email = realCustomer.Email;
                    }

                }

                //  _customerService.UpdateCustomer(customer);
            }

            void DebugLog(string text)
            {
#if DEBUG
                Logger.Default.Debug(text);
#endif
            }

            public void OnActionExecuting(ActionExecutingContext context)
            {
                const string COOKIE_TOKEN = "Nop.UC.Token";

                bool hasLogin = true;
                if (!context.HttpContext.Request.Cookies.ContainsKey(COOKIE_TOKEN))
                {
                    hasLogin = false;
                }
                StringValues values = new StringValues();
                if (!context.HttpContext.Request.Headers.TryGetValue("UC_TOKEN", out values))
                {
                    values = new StringValues();
                    if (!context.HttpContext.Request.Headers.TryGetValue("authtoken", out values))
                    {
                        hasLogin = false;
                    }
                }
                var token = values.Count > 0 ? values.Take(1).SingleOrDefault() : "";
                if (hasLogin && String.IsNullOrEmpty(token))
                {
                    hasLogin = false;
                }
                if (hasLogin && !token.Equals(context.HttpContext.Request.Cookies[COOKIE_TOKEN]))
                {
                    hasLogin = false;
                }
                if (hasLogin && !_workContext.CurrentCustomer.IsRegistered())
                {
                    hasLogin = false;
                }
                if (!hasLogin && !String.IsNullOrEmpty(token))
                {
                    bool hasWait = false;
                    lock (processMutexList)
                    {
                        DebugLog($"Url:{context.HttpContext.Request.Path},Token:{token}开始处理");

                        if (tokenOfCustomerIdDict.ContainsKey(token))
                        {
                            DebugLog($"Url:{context.HttpContext.Request.Path},Token:{token}结果集中包含其他线程已处理结果,返回!");
                            SetCustomer(token);
                            DebugLog($"Url:{context.HttpContext.Request.Path},Token:{token}设置当前用户:{  _workContext.CurrentCustomer.Id},Email:{  _workContext.CurrentCustomer.Email}");
                            return;
                        }
                        if (processMutexList.ContainsKey(token))
                        {
                            DebugLog($"Url:{context.HttpContext.Request.Path},Token:{token}已存在,开始等待");
                            if (!processMutexList[token].WaitOne(3 * 1000))
                            {
                                throw new Exception("在处理用户凭据时,线程互斥锁获取错误");
                            }
                            hasWait = true;

                        }
                        else
                        {
                            DebugLog($"Url:{context.HttpContext.Request.Path},Token:{token}不存在加入锁");
                            processMutexList[token] = new AutoResetEvent(false);
                        }
                    }
                    if (hasWait)
                    {
                        DebugLog($"Url:{context.HttpContext.Request.Path},Token:{token}其他请求已处理完");
                        if (tokenOfCustomerIdDict.ContainsKey(token))
                        {
                            DebugLog($"Url:{context.HttpContext.Request.Path},Token:{token}结果集中包含结果");
                            SetCustomer(token);
                            DebugLog($"Url:{context.HttpContext.Request.Path},Token:{token}设置当前用户:{  _workContext.CurrentCustomer.Id},Email:{  _workContext.CurrentCustomer.Email}");
                        }
                        else
                        {
                            DebugLog($"Url:{context.HttpContext.Request.Path},Token:{token}结果集中不包含结果");
                            _workContext.CurrentCustomer = null;
                        }
                        return;
                    }

                    try
                    {
                        var sdk = _hUCSdkHelper.Get();
                        var result = sdk.CheckTokenAsync(token).GetAwaiter().GetResult();
                        if (result.Success)
                        {
                            var member = _cacheManager.Get<UCMemberResult>(nameof(UserCenterFilter) + nameof(UserCenterFilter) + result.MemberId, () =>
                            {
                                var memberResult = sdk.GetMemberAsync<UCMemberResult>(result.MemberId).GetAwaiter().GetResult();
                                if (memberResult.Success)
                                {
                                    bool setExt = false;
                                    if (string.IsNullOrEmpty(memberResult.NickName))
                                    {
                                        setExt = true;
                                        memberResult.NickName = memberResult.UserName.Substring(0, 3) + "****" + memberResult.UserName.Substring(memberResult.UserName.Length - 4, 4);
                                    }
                                    if (string.IsNullOrEmpty(memberResult.Email))
                                    {
                                        setExt = true;
                                        memberResult.Email = $"HUC_Member_{memberResult.MemberId}@hsq168.co";
                                    }
                                    if (setExt)
                                    {
                                        sdk.SetExtAsync(result.MemberId, $"{{\"nickName\":\"{ memberResult.NickName}\", \"email\":\"{  memberResult.Email }\"}}");
                                    }
                                    return memberResult;
                                }
                                return null;

                            }, cacheTime: 1);
                            if (member != null)
                            {
                                var customer = _customerService.GetCustomerByEmail($"HUC_Member_{member.MemberId}@hsq168.co");
                                if (customer != null)
                                {
                                    Login(token, customer);
                                }
                                else
                                {
                                    Register(member.Email, member.MemberId, token);
                                    //string easeUserName = string.Format("huc_{0}_nop_{1}", member.MemberId, customer.Id);
                                    //_easemobManager.RegisterUser(easeUserName, easeUserName);
                                }
                                context.HttpContext.Response.Cookies.Append("Nop.UC.Token", token);
                            }
                        }
                    }
                    finally
                    {
                        DebugLog($"Url:{context.HttpContext.Request.Path},Token:{token}登录过程完成移除锁");
                        processMutexList.Remove(token, out AutoResetEvent semaphore);
                        semaphore.Set();
                    }

                }
                else if (string.IsNullOrEmpty(token))
                {
                    if (_workContext.CurrentCustomer.IsRegistered())
                    {
                        Logout();
                    }
                }


            }
        }
    }
}
